﻿using System.Collections.ObjectModel;
using CommunityToolkit.WinUI.UI.Controls;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using WhaleAccount.Contracts.Services;
using WhaleAccount.Models;
using WhaleAccount.ViewModels;
using Windows.Foundation.Metadata;
using Type = WhaleAccount.Models.Type;

namespace WhaleAccount.Views;

public sealed partial class MainPage : Page
{
    private readonly IRecordService _recordService;
    private readonly ITypeService typeService;
    public MainViewModel ViewModel
    {
        get;
    }

    public ObservableCollection<Type> TypeList
    {
        get; set;
    } = new ObservableCollection<Type>();

    public MainPage()
    {
        _recordService = App.GetService<IRecordService>();
        typeService = App.GetService<ITypeService>();
        ViewModel = App.GetService<MainViewModel>();

        InitializeComponent();
        DatePicker.Date = DateTime.Now;
        DateCalendarDatePicker.Date = DateTime.Now;
    }

    private void OnViewStateChanged(object sender, ListDetailsViewState e)
    {
        if (e == ListDetailsViewState.Both)
        {
            ViewModel.EnsureItemSelected();
        }
    }

    private void DatePicker_SelectedDateChanged(DatePicker sender, DatePickerSelectedValueChangedEventArgs args)
    {
        if (args.NewDate != null)
        {
            var value = args.NewDate.Value;
            ViewModel.LoadData(value.Year, value.Month);
        }
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        AddTip.IsOpen = true;
    }

    private void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        var record = new Record
        {
            Category = ExpenseRadioButton.IsChecked.GetValueOrDefault(true) ? 0 : 1,
            Type = (int)TypeComboBox.SelectedValue,
            Value = ValueNumberBox.Value,
            Date = DateCalendarDatePicker.Date.GetValueOrDefault(DateTime.Now).DateTime,
            Remark = RemarkTextBox.Text
        };

        _recordService.AddRecordAsync(record);
        ViewModel.LoadData(record.Date.Year, record.Date.Month);
        AddTip.IsOpen = false;

        // 清空金额
        ValueNumberBox.Text = null;
        // 清空备注
        RemarkTextBox.Text = null;

        DatePicker.Date = record.Date;
        ViewModel.EnsureItemSelected(record.Date);
    }

    private async void DeleteButton_Click(object sender, RoutedEventArgs e)
    {
        var deleteConfirmDialog = new ContentDialog()
        {
            Title = "删除确认",
            Content = "确定删除这些记录吗？",
            PrimaryButtonText = "删除",
            CloseButtonText = "取消",
            DefaultButton = ContentDialogButton.Primary
        };

        // Use this code to associate the dialog to the appropriate AppWindow by setting
        // the dialog's XamlRoot to the same XamlRoot as an element that is already present in the AppWindow.
        if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
        {
            deleteConfirmDialog.XamlRoot = ListDetailsViewControl.XamlRoot;
        }

        var result = await deleteConfirmDialog.ShowAsync();

        if (result == ContentDialogResult.Primary)
        {
            if (ListDetailsViewControl.SelectedItem is DayRecordSummary dayRecordSummary)
            {
                var selectedRecords = dayRecordSummary.SelectedRecords;
                if (selectedRecords.Count > 0)
                {
                    DateTime date = default;
                    for (var i = 0; i < selectedRecords.Count; i++)
                    {
                        var item = selectedRecords[i];
                        date = item.Date;
                        await _recordService.DeleteRecordsAsync(item);
                    }

                    ViewModel.LoadData(DatePicker.Date.Year, DatePicker.Date.Date.Month);
                    if (date == default)
                    {
                        ViewModel.EnsureItemSelected();
                    }
                    else
                    {
                        ViewModel.EnsureItemSelected(date);
                    }
                }
            }
        }
    }

    private void BulletsButton_Click(object sender, RoutedEventArgs e)
    {
        if (ViewModel.Selected != null)
        {
            if (ViewModel.Selected.IsSelectale)
            {
                ViewModel.Selected.IsSelectale = false;
                DeleteButton.Visibility = Visibility.Collapsed;
            }
            else
            {
                ViewModel.Selected.IsSelectale = true;
                DeleteButton.Visibility = Visibility.Visible;
            }
        }
    }

    private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        if (ViewModel.Selected != null)
        {
            ViewModel.Selected.IsEditable = !ViewModel.Selected.IsEditable;
            foreach (var record in ViewModel.Selected.Records)
            {
                record.IsEditable = ViewModel.Selected.IsEditable;
            }
        }
    }

    private void ListDetailsViewControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        foreach (var item in e.RemovedItems)
        {
            if (item is DayRecordSummary dayRecordSummary)
            {
                DeleteButton.Visibility = Visibility.Collapsed;
                // 清空多选状态
                dayRecordSummary.IsSelectale = false;
                // 清空编辑状态
                dayRecordSummary.IsEditable = false;
                foreach (var record in dayRecordSummary.Records)
                {
                    record.IsEditable = false;
                }
            }
        }
    }

    private void ExpenseRadioButton_Checked(object sender, RoutedEventArgs e)
    {
        FillTypes(0);
    }

    private void IncomeRadioButton_Checked(object sender, RoutedEventArgs e)
    {
        FillTypes(1);
    }

    /// <summary>
    /// 填充收支类型列表
    /// </summary>
    /// <param name="category">分类</param>
    private void FillTypes(int category)
    {
        TypeList.Clear();

        var types = typeService.GetTypeListAsync().Result;
        foreach (var type in types)
        {
            if (type.Visible && type.Category == category)
            {
                TypeList.Add(type);
            }
        }

        if (TypeComboBox != null)
        {
            TypeComboBox.SelectedIndex = 0;
        }
    }
}
